package com.plusjun.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class HelloController {
    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录访问
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }

    /**
     * @param model
     * @param session
     * @param token   : 从ssoServer中跳回来的请求中携带了 token
     * @return
     */
    @GetMapping("/boss")
    public String employees(Model model, HttpSession session,
                            @RequestParam(required = false, value = "token") String token) {
        if (!StringUtils.isEmpty(token)) {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8080/info?token=" + token, String.class);
            String name = entity.getBody();
            session.setAttribute("loginUser", name);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            // 没登陆就去登录页
            // 带上自己的需要调回的页面

            return "redirect:" + ssoServerUrl + "?redirect_url=http://client2.com:8082/boss";
        }
        List<String> employees = new ArrayList<>();
        employees.add("张三");
        employees.add("李四");
        model.addAttribute("emps", employees);
        return "list";
    }


}
